# This file is part of Sonedyan.
#
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2009-2012 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>

source('motifs.R')
source('cycles.R')
source('metrics.R')

#seed <- read.graph(file = "fa-seed-graphml.xml", format = "graphml")

print.stats <- function(name, stats)
{
	print(paste(name, " #v:", stats[["nv"]]))
	print(paste(name, " #e:", stats[["ne"]]))
	print(paste(name, " density:", stats[["dens"]]))
	print(paste(name, " CPL:", stats[["cpl"]]))
	print(paste(name, " diameter (d):", stats[["ddiam"]]))
	print(paste(name, " diameter (u):", stats[["udiam"]]))
	print(paste(name, " avg deg:", stats[["avgdeg"]]))
}

###
# motifs 
###

#adj <- get.adjacency(seed)

# alpha motif (2 isolated triangles with a maximum of 6 shortcuts)

# beta motif (2 triangles with one vertex in common and a maximum of 4 shortcuts)

# delta motif (2 triangles with 2 vertices in common and a colink)
#d0 <- matrix(c(0,1,1,1, 0,0,1,0, 1,0,0,0, 0,0,1,0), nrow = 4, byrow = TRUE)

# gamma motif (2 triangles with 2 vertices in common and maximum 2 shortcuts)
#g0 <- matrix(c(0,1,0,1, 0,0,1,0, 1,0,0,0, 0,0,1,0), nrow = 4, byrow = TRUE)
#g1a <- matrix(c(0,1,0,1, 0,0,1,1, 1,0,0,0, 0,0,1,0), nrow = 4, byrow = TRUE)
#g1b <- matrix(c(0,1,0,1, 0,0,1,0, 1,0,0,0, 0,1,1,0), nrow = 4, byrow = TRUE)
#g2 <- matrix(c(0,1,0,1, 0,0,1,1, 1,0,0,0, 0,1,1,0), nrow = 4, byrow = TRUE)

#count <- count.motif(adj, d0)

###
# 3-cycles reduction
###

#c3 <- get.cycles(seed, 3)
#seed3 <- get.cycles.subgraph.reduction(c3$cn)

#write.graph(seed3, file= "fa-seed3-graphml.xml", format = "graphml")
#write.graph(seed3, file= "fa-seed3-gml.gml", format = "gml")

#seed3 <- read.graph(file = "fa-seed3-graphml.xml", format = "graphml")

metrics <- c("cpl", "ddiam", "udiam", "dens", "nv", "ne", "avgdeg")
#stats <- get.graph.stats(seed3, metrics)

#print.stats("Seed3", stats)

#e1 <- E(seed3)[E(seed3)$weight == 1]

#seed32 <- delete.edges(seed3, e1)

#write.graph(seed32, file= "fa-seed3-e2-graphml.xml", format = "graphml")
#write.graph(seed32, file= "fa-seed3-e2-gml.gml", format = "gml")

#seed32 <- read.graph(file = "fa-seed3-e2-graphml.xml", format = "graphml")

#stats <- get.graph.stats(seed32, metrics)
#print.stats("Seed3-e2", stats)

#ccs = clusters(seed32)
#maxCcSize <- max(ccs$csize)
# igraph is 0 based but R is 1 based...
#maxCcId = which(ccs$csize == maxCcSize)[1] - 1
#vids <- (which(ccs$membership == maxCcId) - 1)

#seed32.core <- subgraph(seed32, vids)

#write.graph(seed32.core, file= "fa-seed32-core-graphml.xml", format = "graphml")
#write.graph(seed32.core, file= "fa-seed32-core-gml.gml", format = "gml")
seed32.core <- read.graph(file = "fa-seed32-core-graphml.xml", format = "graphml")

mcliques <- maximal.cliques(seed32.core)
#saveRDS(mcliques, "fa-seed32-core-mcliques.rds")

nc <- length(mcliques)
cliques <- list()

for (i in c(1:nc))
{
	nodes <- V(seed32.core)[mcliques[[i]]]$name
	words <- c()

	for (j in c(1:length(nodes)))
	{
		node <- nodes[[j]]

		for (z in strsplit(node, "\\."))
		{
			words <- append(words, z)
		}
	}

	words <- unique(words)
	cliques[[i]] <- words
}

# cliques sorted by size
scliques <- list()

cl <- lapply(cliques, length)
minl <- min(unlist(cl))
maxl <- max(unlist(cl))

for (p in c(minl:maxl))
{
	ids <- which(cl == p)
	scliques <- append(scliques, cliques[ids])
}

# reduced list of words
rcliques <- list()
counter <- 1

for (i in c(1:(nc-1)))
{
	is.subset <- FALSE

	for (j in c((i+1):nc))
	{
		ci <- scliques[[i]]
		cj <- scliques[[j]]

		if (!(any(ci %in% cj == FALSE)))
		{
			is.subset <- TRUE
			break
		}
	}
	
	if (!is.subset)
	{
		rcliques[[counter]] <- scliques[[i]]
		counter <- counter + 1
	}
}


# get cliques size
#rcl <- lapply(rcliques, length)

#for (i in c(4:17))
#{
#	lx <- length(which(rcl == i))
#	print(paste("#", i, ":", lx))
#}

rcg <- graph.empty(directed = FALSE)
cnames <- c()

for (rc in c(1:length(rcliques)))
{
	cnames <- append(cnames, paste(rcliques[[rc]], collapse = "."))	
}

lcn <- length(cnames)
rcg <- add.vertices(rcg, lcn)
# set the vertices name
rcg <- set.vertex.attribute(rcg, "name", V(rcg), cnames)

redges <- c()
weights <- c()

for (i in c(1:(lcn-1)))
{
	wi <- strsplit(rcliques[[i]], "\\.")
	for (j in c((i+1):lcn))
	{
		wj <- strsplit(rcliques[[j]], "\\.")
		il <- length(intersect(wi, wj))

		if (il > 0)
		{
			# 1-based?
			redges <- append(redges, c(i, j))
			weights <- append(weights, il)
		}
	}
}

print(length(redges))
print(length(weights))

rcg <- add.edges(rcg, redges)
E(rcg)$weight <- weights

stats <- get.graph.stats(rcg, metrics)
print.stats("Seed32 core cliques", stats)

write.graph(rcg, file= "fa-seed32-core-cliques-graphml.xml", format = "graphml")
write.graph(rcg, file= "fa-seed32-core-cliques-gml.gml", format = "gml")
